package com.elective.courseselect.controller;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lee
 * @date 2021年10月24日 19:55
 */
@RestController
@RequestMapping("/quartz")
public class QuartzScheduleController {

    /**
     * 开始执行任务
     * @return
     * @throws ClassNotFoundException
     * @throws SchedulerException
     */
    @GetMapping("/start")
    public String start() throws ClassNotFoundException, SchedulerException {
        Scheduler scheduler = createScheduler();
        scheduler.start();
        return "执行任务！！！！！";
    }

    /**
     * 停止执行任务
     * @return
     * @throws SchedulerException
     * @throws ClassNotFoundException
     */
    @GetMapping("/stop")
    public String stop() throws SchedulerException, ClassNotFoundException {
        StdSchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();
        JobKey jobKey = new JobKey("myStoppableJob");
        scheduler.pauseJob(jobKey);
        scheduler.deleteJob(jobKey);
        return "停止任务！！！！！";
    }

    /**
     * 新建任务
     * @return
     * @throws SchedulerException
     * @throws ClassNotFoundException
     */
    public Scheduler createScheduler() throws SchedulerException, ClassNotFoundException {
        JobDetail jobDetail = JobBuilder.newJob(getMyClass()).withIdentity("myStoppableJob").build();
        SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().withIdentity("myStoppableTrigger").startNow().withSchedule(
                SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()).build();
        StdSchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();
        scheduler.scheduleJob(jobDetail, simpleTrigger);
        return scheduler;
    }

    /**
     * 通过类路径获取类
     * @return
     * @throws ClassNotFoundException
     */
    private Class getMyClass() throws ClassNotFoundException {
        Class myClass = Class.forName("com.cobra.quartzlearn.job.MyJob");
        return myClass;
    }

}